/**
 * storage封装
 * localStorage、sessionStorage
 * */

class StorageTool {
  // 默认使用localStorage
  private storage = window.localStorage;

  constructor(mode: StorageMode = "local") {
    const storageMap: Record<StorageMode, any> = {
      local: window.localStorage,
      session: window.sessionStorage
    };
    if (storageMap[mode]) {
      this.storage = storageMap[mode];
    }
  }

  /**
   * 读取缓存
   * @param {string} key - 读取的缓存key
   * @return {any} - 返回拿到的value，首先尝试转JSON，成功则使用JSON，不成功则原样返回(返回的是string)
   * */
  get(key: string = ""): any {
    if (!key) {
      console.error("缺少必传参数key");
      return "";
    }

    let value: any = this.storage.getItem(key);

    try {
      value = JSON.parse(value);
      if (typeof value === "number") value = String(value);
    } catch (error) {
      /* empty */
    }

    return value;
  }

  /**
   * 设置缓存
   * @param {string} key - 缓存key
   * @param {any} value - 缓存value，如果是数组或JSON则转为json字符串存储，否则原样存储(会默认转string)
   * @return {any} 将存储的值返回
   * */
  set(key: string = "", value: any = ""): any {
    if (!(key && value)) {
      console.log("key和value不可为空");
      return "";
    }
    // json或数组，转为json字符串存储
    if (String(value) === "[object Object]" || Array.isArray(value)) {
      value = JSON.stringify(value);
    }

    this.storage.setItem(key, value);

    return this.get(key);
  }

  /**
   * 移除缓存
   * @param {string} key - 缓存key
   * */
  remove(key: string = "") {
    if (!key) return console.error("缺少缓存key");
    this.storage.removeItem(key);
  }
}

export const LocalStorage = new StorageTool("local");

export const SessionStorage = new StorageTool("session");

/**
 * storage的存储模式
 * local：使用localStorage
 * session：使用sessionStorage
 * */
declare type StorageMode = "local" | "session";
